package com.neo.push.core;

import com.alibaba.fastjson.JSON;

import java.io.UnsupportedEncodingException;

/**
 * Created by lock on 17-7-11.
 */
public enum MessageType implements MessageDecoder {

    PING((short)1){
        @Override
        public Message decode(byte[] content) {
            return new PingMessage();
        }
    },PONG((short)2){
        @Override
        public Message decode(byte[] content) {
            return new PongMessage();
        }
    },TEXT((short)3){
        @Override
        public Message decode(byte[] content) {
            return new TextMessage(content);
        }
    },RECEIPT((short)4){
        @Override
        public Message decode(byte[] content) {
            try {
                return new Receipt(new String(content,"UTF-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            return null;
        }
    },REGISTER((short)5){
        @Override
        public Message decode(byte[] content) {
            return new SocketRegisterMessage((RegisterMessage) JSON.parseObject(content,RegisterMessage.class));
        }
    },S_PUSH((short)6){
        @Override
        public Message decode(byte[] content) {
            return new SafetyPushText((AcceptPush)JSON.parseObject(content,AcceptPush.class));
        }
    };

    private short code;

    MessageType(short code) {
        this.code = code;
    }

    public short getCode() {
        return code;
    }

    public static MessageType instance(short type) {
        for(MessageType t : values()){
            if(t.getCode()==type){
                return t;
            }
        }
        throw new RuntimeException(" message not supported exception !");
    }
}
